package com.shushan.pages;

import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.shushan.base.BaseActivity;
import com.shushan.base.BaseExerciseHeaderActivity;
import com.shushan.base.Constants;
import com.shushan.base.NavigationLoseActivity;
import com.shushan.base.ScreenManager;
import com.shushan.exam.ExamActivity;
import com.shushan.home.bean.LearnByDoBean;
import com.shushan.home.bean.RewardTimeBean;
import com.shushan.home.bean.RewardToyBean;
import com.shushan.mixedexam.MixedExamActivity;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.BuildConfig;
import com.shushan.shushanbao.R;
import com.shushan.util.DialogUtil;
import com.shushan.util.ImageUtils;
import com.shushan.util.Session;
import com.shushan.util.ToolUtils;

import java.util.ArrayList;
import java.util.HashMap;

import cn.jzvd.JZVideoPlayer;
import cn.jzvd.JZVideoPlayerStandard;

/**
 * @ClassName: NewStudyWithExerciseActivity
 * @Desciption: //新边学边练页面：使用第三方播放器
 * @author: zhangshihao
 * @date: 2018-06-12
 */
public class NewStudyWithExerciseActivity extends BaseExerciseHeaderActivity implements View.OnClickListener,
        JZVideoPlayerStandard.OnVideoFinishListener{

    private static final String TAG = NewStudyWithExerciseActivity.class.getSimpleName();

    //@布局元素{
    //专题名
    private TextView tvSpecialTopicTitle;
    //专题老师
    private TextView tvTeacherName;
    //科目名
    private TextView tvSubjectName;
    //专题描述
    private TextView tvSpecialTopicDes;
    //获得时间奖励条件
    private TextView tvAwardTimeDes;

    //专题图片
    private ImageView ivSpecialTopicImg;

    private View timeLable;

    private ImageView ivChangeSpecialTopic;
    //@}

    //视频元素@{
    private JZVideoPlayerStandard jzVideoPlayerStandard;
    private Bitmap firstFrame;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            jzVideoPlayerStandard.thumbImageView.setImageBitmap(firstFrame);
        }
    };
    //@}
    private int subjectId;
    private int position;
    private int addIndex;
    private int videoId;
    private ArrayList<LearnByDoBean> learnByDoBeanList;
    private LearnByDoBean currentLearnByDo;
    private BabyApplication shuShanApplication = BabyApplication.getInstance();
    private int score,time;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_study_with_exercise_new);
        setTitle("边学边练");

        subjectId = getIntent().getIntExtra("subjectId",0);
        position = getIntent().getIntExtra("position",0);
        addIndex = position;
        score = getIntent().getIntExtra("score",0);
        time = getIntent().getIntExtra("time",0);
        learnByDoBeanList = (ArrayList<LearnByDoBean>) Session.getSession().get("learnByDoBeanList");

        initView();

        initData(position);
    }

    private void initView(){
        tvSpecialTopicTitle = findViewById(R.id.tv_special_topic_title);
        tvTeacherName = findViewById(R.id.tv_teacher_name);
        tvSubjectName = findViewById(R.id.tv_subject_name);
        tvSpecialTopicDes = findViewById(R.id.tv_special_topic_des);
        tvAwardTimeDes = findViewById(R.id.tv_award_time_des);
        ivSpecialTopicImg = findViewById(R.id.iv_special_topic_pic);
        ivChangeSpecialTopic = findViewById(R.id.iv_change_special_topic);
        ivChangeSpecialTopic.setOnClickListener(this);
        timeLable = findViewById(R.id.view_3);
        jzVideoPlayerStandard = findViewById(R.id.video_view);
        jzVideoPlayerStandard.setOnVideoFinishListener(this);
    }

    private void initData(int position){
        if(ToolUtils.isListEmpty(learnByDoBeanList)){
            return;
        }
        setHeaderText(shuShanApplication.getCurrentChildBean(),score,time);

        currentLearnByDo = learnByDoBeanList.get(position);
        if(currentLearnByDo != null){
            setFirstFrameDrawable(currentLearnByDo.video_url);

            jzVideoPlayerStandard.setUp(currentLearnByDo.video_url,JZVideoPlayerStandard.SCREEN_WINDOW_NORMAL,currentLearnByDo.video_title);

            videoId = currentLearnByDo.id;

            tvSpecialTopicTitle.setText(currentLearnByDo.video_title);
            tvTeacherName.setText("讲师： " + currentLearnByDo.video_teacher);
            tvSubjectName.setText("科目： " + ToolUtils.getSubjectNameFromId(subjectId));
            tvSpecialTopicDes.setText(currentLearnByDo.video_desc);

            ImageUtils.loadImageView(this,currentLearnByDo.cover,ivSpecialTopicImg);

        }else {
            showToast("信息为空");
            return;
        }
    }

    private void setFirstFrameDrawable(final String url){
        new Thread(new Runnable() {
            @Override
            public void run() {
                MediaMetadataRetriever mmr = new MediaMetadataRetriever();
                Log.d(TAG,"video_url = "+url);
                String loadUrl;
                if(ImageUtils.isAbsoluteUrl(url)){
                    loadUrl = url;
                }else{
                    loadUrl = BuildConfig.imgBaseUrl+url;
                }
                Log.d(TAG,"loadUrl = "+loadUrl);
                try {
                    mmr.setDataSource(loadUrl,new HashMap<String, String>());
                    firstFrame = mmr.getFrameAtTime();
                    mHandler.sendEmptyMessage(0);
                }catch (IllegalArgumentException ex){
                    ex.printStackTrace();
                }catch (RuntimeException ex){
                    ex.printStackTrace();
                } finally {
                    try {
                        mmr.release();
                    } catch (RuntimeException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }).start();
    }

    @Override
    public void onBackPressed() {
        if (JZVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        JZVideoPlayer.releaseAllVideos();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_continue_study://我想再学学
                DialogUtil.dismissDialog();
                break;
            case R.id.btn_start_exercise://学会了，开始练习
                startExam();
                break;
            case R.id.iv_change_special_topic:
                changeTeacher();
                break;
        }
    }

    private void startExam() {
        DialogUtil.dismissDialog();

        Intent intent = new Intent(this, MixedExamActivity.class);
        intent.putExtra("examType", Constants.TYPE_LEARN_BY_DO);
        intent.putExtra("subjectId", subjectId);
        intent.putExtra("videoId", videoId);
        intent.putExtra("awardType", 3);
        startActivityAllow(intent);
    }

    private void changeTeacher() {
        if(ToolUtils.isListEmpty(learnByDoBeanList)){
            showToast("列表为空");
            return;
        }

        int size = learnByDoBeanList.size();
        if(size < 2){
            showToast("没有更多的老师");
            return;
        }

        addIndex++;
        currentLearnByDo = learnByDoBeanList.get(addIndex % size);
        if(currentLearnByDo != null){
//            if(jzVideoPlayerStandard.isCurrentPlay()){
            setFirstFrameDrawable(currentLearnByDo.video_url);
                jzVideoPlayerStandard.release();
                jzVideoPlayerStandard.setUp(currentLearnByDo.video_url,JZVideoPlayerStandard.SCREEN_WINDOW_NORMAL,currentLearnByDo.video_title);
//            }
            videoId = currentLearnByDo.id;

            tvSpecialTopicTitle.setText(currentLearnByDo.video_title);
            tvTeacherName.setText("讲师： " + currentLearnByDo.video_teacher);
            tvSubjectName.setText("科目： " + ToolUtils.getSubjectNameFromId(subjectId));
            tvSpecialTopicDes.setText(currentLearnByDo.video_desc);

            ImageUtils.loadImageView(this,currentLearnByDo.cover,ivSpecialTopicImg);

        }
    }

    @Override
    public void onVideoFinish() {
        DialogUtil.showVideoFinishDialog(this, this);
    }
}
